package cn.geminis.warehouse.service.basic.entity;

import cn.geminis.lowcode.annotation.*;
import cn.geminis.warehouse.service.basic.entity.filter.ProductFilter;
import cn.geminis.warehouse.service.basic.entity.repository.ProductRepository;
import cn.geminis.warehouse.service.util.JsonNodeConverter;
import cn.geminis.warehouse.service.util.SpringApplicationContext;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.vladmihalcea.hibernate.type.json.JsonType;
import jakarta.persistence.Column;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Type;

import java.math.BigDecimal;

/**
 * 商品
 */
@Getter
@Setter
@UuidEntity(idFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@SoftDeleteEntity(deleteFieldAnnotations = {"com.alibaba.excel.annotation.ExcelIgnore"})
@QueryFilter
@CrudRepository
@CrudController
@ExcelController
//@Table(uniqueConstraints = {@UniqueConstraint(columnNames = "no")})
public class Product {

    /**
     * 名称
     */
    @Column(nullable = false)
    @ExcelProperty("名称")
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String name;

    /**
     * 编号
     */
    @Column(nullable = false)
    @ExcelProperty("编号")
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like, valueFormat = "%%%s%%")
    private String no;

    /**
     * 属性
     */
    @Type(JsonType.class)
    @Column(columnDefinition = "json")
    @ExcelProperty(value = "属性", converter = JsonNodeConverter.class)
    private JsonNode properties;

    /**
     * 装卸单价
     */
    @Column(nullable = false)
    @ExcelProperty("装卸单价")
    private BigDecimal priceLoad;


    public static class ProductConverter implements Converter<Product> {
        @Override
        public Product convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            var productName = cellData.getStringValue();
            var repository = SpringApplicationContext.getBean(ProductRepository.class);
            return repository.findOne(ProductFilter.builder().name(productName).deleted(false).build()).get();
        }

        @Override
        public WriteCellData<?> convertToExcelData(Product value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            return new WriteCellData<>(value.name);
        }
    }

}
